package cn.ljy.uem.web.websocket.config;

import cn.ljy.authority.config.security.TokenUtil;
import cn.ljy.authority.service.SysUserTokenFrontendService;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.model.result.ResultCode;
import cn.ljy.common.utils.ResponseUtil;
import cn.ljy.uem.service.SchoolStudentService;
import cn.ljy.uem.service.SchoolTeacherService;
import cn.ljy.uem.service.common.CommonSchoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * websocket的登录拦截器
 */
@Component
@Slf4j
public class UserLoginWebsocketInterceptor implements HandshakeInterceptor {
    @Autowired
    private SchoolTeacherService schoolTeacherService;
    @Autowired
    private SchoolStudentService schoolStudentService;
    @Autowired
    private SysUserTokenFrontendService sysUserTokenFrontendService;
    @Autowired
    private CommonSchoolService commonSchoolService;

    /**
     * 握手前，在连接第一次加入时生效
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return false表示不通过
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        boolean flag=false;
        // 初始化request信息
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        ServletServerHttpResponse servletResponse = (ServletServerHttpResponse) response;
        //读取前台token的值,websocket必须通过Sec-WebSocket-Protocol读取
//        String token= TokenUtil.getAppToken();
        String token= TokenUtil.getAppTokenFromWebSocket(servletRequest.getServletRequest());
        log.debug("websocket接收的token:{}",token);
        if(StringUtils.hasLength(token)){
            //必须要在这里重新给Sec-WebSocket-Protocol赋值，否则会导致连接后立即中断。但是要注意，如果是uniapp连接则不能传送
            if(StringUtils.hasLength(servletRequest.getServletRequest().getHeader("Sec-WebSocket-Protocol"))){
                servletResponse.getServletResponse().setHeader("Sec-WebSocket-Protocol",token);
            }
            //由于在websocket发送信息，如handleMessage中无法获取token信息，因此拦截器这里获取到token后再重新做一个赋值
            //在handleMessage可以通过session.getAttributes().get("token").toString();获取token的值
            attributes.put("token", token);
            //获取网址最后一个/后的字符串，作为课堂id
            String url=servletRequest.getServletRequest().getServletPath();
            String lessonId = url.substring(url.lastIndexOf("/")+1);
            attributes.put("lessonId", lessonId);
            flag=true;
        }else{
            ResponseUtil.responseJson(servletResponse.getServletResponse(), ResponseData.error(ResultCode.UNAUTHORIZED.getCode(),"操作失败：请先登录"));
        }
        return flag;
    }

    /**
     * 握手后
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("握手后");
    }
}
